#include "GraphicsDevice.h"
GraphicsDevice::GraphicsDevice(int w, int h) :width(w), height(h)
{
	//初始化SDL
    if (SDL_Init(SDL_INIT_VIDEO) != 0)
    {
        std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
    }
 
    //创建窗口
    win = nullptr;
    win = SDL_CreateWindow("SDL2",
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        width, height, SDL_WINDOW_SHOWN);
    if (win == nullptr)
    {
        std::cout << SDL_GetError() << std::endl;
    }
 
    //创建渲染器
    ren = nullptr;
    ren = SDL_CreateRenderer(win, -1,
        SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (ren == nullptr)
    {
        std::cout << SDL_GetError() << std::endl;
    }
 
    //创建表面
    bmp = nullptr;
    bmp = SDL_GetWindowSurface(win);
    if (bmp == nullptr) {
        std::cout << SDL_GetError() << std::endl;
    }
 
    //创建材质
    tex = nullptr;

	g_pBuf = (DWORD*)bmp->pixels;//获取显存
	backBuffer = new DWORD[width * height];
}

void GraphicsDevice::SetPixel(int x, int y, COLORREF c)
{
	y = (int)height - 1 - y;//因为easyx的y值0点是最上面，所以将屏幕上下翻转到最下面
	g_pBuf[y * width + x] = BGR(c);
	tex = SDL_CreateTextureFromSurface(ren, bmp);
 
    //清空渲染器
    SDL_RenderClear(ren);
    //将材质复制到渲染器
    SDL_RenderCopy(ren, tex, NULL, NULL);
	SDL_RenderPresent(ren);
}
void GraphicsDevice::SetPixel_Back(int x, int y, COLORREF c)
{
	y = (int)height - 1 - y;//因为easyx的y值0点是最上面，所以将屏幕上下翻转到最下面
	backBuffer[y * width + x] = BGR(c);
}
void GraphicsDevice::flush()
{
	std::copy(backBuffer, backBuffer + height * width, g_pBuf);
	tex = SDL_CreateTextureFromSurface(ren, bmp);
    SDL_RenderClear(ren);
    SDL_RenderCopy(ren, tex, NULL, NULL);
	SDL_RenderPresent(ren);
}
void GraphicsDevice::clear_color_bcak(COLORREF c)
{
	std::fill(backBuffer, backBuffer + ((size_t)height * (size_t)width), c);
}
GraphicsDevice::~GraphicsDevice()
{
	delete backBuffer;
	    //释放资源
    SDL_DestroyTexture(tex);
    SDL_DestroyRenderer(ren);
	SDL_FreeSurface(bmp);
    SDL_DestroyWindow(win);
    //退出SDL
    SDL_Quit();
}